(function(win, doc) {

	'use strict';

	var editBox = $("#edit-box"),
		edit = $("#edit"),
		editChartlet = $("#edit-chartlet"),
		templetImage = $("#templet-image").clone(),
		userImage = $("#user-image"),
		_self = null;

	var click = "ontouchstart" in doc ? "touchstart" : "click";
	/**
	 * 主函数
	 *
	 */
	function Custom (options) {
		this.options = options;

		// 初始化
		this.init();
	};


	/**
	 * 初始化
	 */
	Custom.prototype.init = function() {

		_self = this;

		var _options = _self.options;

        // 带虚线外框的图片；
        // <img id="edit-mask" class="edit-mask" width="100%" src="http://zhenfei.jumpcity.cn/uploads/basemap/20170720/49f91930b4fad4f1a0cb960ff2319460.png"> 真实尺寸是 2200 * 2200，显示到手机屏幕上会进行缩放，因为指定了宽度，所以是等比例的缩放；
        // console.log(_options.mask.src);
        $("#edit-mask").attr("src", _options.mask.src);

		// 设置mask有效位置、尺寸
		var calc = function(num) {
			return (num / _options.mask.width * 100).toFixed(2) + "%";
		};
        // _options.mask.width = 2200；

		edit.css({
			width: calc(_options.react.width),// _options.react.width 虚线框的宽度；
            height: calc(_options.react.height),// _options.react.width 虚线框的高度；
			left: calc(_options.react.x),
			top: calc(_options.react.y)
		});

		// 是否允许用户上传素材
		if (_options.allowUpload) {
			doc.body.classList.add("allow-upload");
		}

		// 选择素材
		$("#edit-choose-img").on("change", _self.chooseImg);

		// 选择模板（tab 萌板 对应的列表）
		// $(".check-nav-list:eq(0) li .tab").click(_self.chooseTemplet);
        $(".check-nav-list:eq(0) li .tab").each(function(index, el) {
            touch.on(this, 'tap', _self.chooseTemplet);// 替换操作；
        });

		// 添加贴图（tab 推荐图案 对应的列表）
		$(".check-nav-list:eq(1) li .tab").each(function () {
            // var that = $(this);
            if(that.attr('data-type') == 'full'){// 手机壳的都是 full。diy。
                // that.click(_self.chooseTemplet);
                touch.on(this, 'tap', _self.chooseTemplet);// 替换操作；
            }else{
                // that.click(_self.addChartlet);
                touch.on(this, 'tap', _self.addChartlet);// 添加操作；意思就是每次都是添加一个贴图到操作区中；
            }
        });

		// 选择贴图
		$(doc).on(click, ".chartlet-item", _self.chooseChartlet);

		// 删除贴图
		// $(doc).on(click, ".chartlet-del", _self.removeChartlet);
	};


	/**
	 * 图片填充满容器
	 */
	var imageCover = function(img) {
		var parent = img.parent();
		var parentWidth = parent.width();
		var parentHeight = parent.height();
		var imgWidth = img[0].naturalWidth;
		var imgHeight = img[0].naturalHeight;

		if (parentWidth / parentHeight > imgWidth / imgHeight) {
			var setHeight = Math.floor(parentWidth / imgWidth * imgHeight);

			img.attr({
				width: Math.floor(parentWidth),
				height: setHeight
			}).css("marginTop", -Math.floor((setHeight - parentHeight) / 2));

		} else {
			var setWidth = Math.floor(parentHeight / imgHeight * imgWidth);

			img.attr({
				width: setWidth,
				height: Math.floor(parentHeight)
			}).css("marginLeft", -Math.floor((setWidth - parentWidth) / 2));
		}
	} ;


	/**
	 * 添加图片
	 */
	Custom.prototype.chooseImg = function() {
		if (this.value === "") {
			return ;
		}

		var fr = new FileReader();

		doc.getElementById("user-add-title").innerHTML = "更换图片";

		fr.onload = function(e) {
			userImage.removeAttr("style").attr("src", e.target.result).data("position", {
				x: 0,
				y: 0,
				rotate: 0,
				scale: 1
			});

			imageCover(userImage);

			$(".chartlet-item").removeClass("active");

			$("body").trigger("update", userImage);
		};

		fr.readAsDataURL(this.files[0]);
	};


	/**
	 * 选择模板（在萌板列表中选择一个）
	 */
	Custom.prototype.chooseTemplet = function() {
		var $this = $(this);
		if ($this.hasClass("null")) {
			$("#templet-image").replaceWith(templetImage[0].outerHTML);
			return ;
		}

		var url = $this[0].getAttribute("data-img");
		var img = new Image();

		img.onload = function() {
			imageCover($("#templet-image"));
		};

		img.src = url;

		$("#templet-image").attr("src", url).data("position", {
			x: 0,
			y: 0,
			rotate: 0,
			scale: 1
		});
	};


	/**
	 * 添加贴图
	 */
	Custom.prototype.addChartlet = function() {
		var $this = $(this);
		var src = $this[0].dataset["img"];
		var div = $(
			"<div class='chartlet-item compose-img active'>"+
				"<span class='chartlet-del'><i class='iconfont icon-delete'></i></span>"+
				"<img src="+ src +" width='100%'>"+
			"</div>"
		);

		div.data("position", {
			x: 0,
			y: 0,
			rotate: 0,
			scale: 1
		});

		editChartlet.children().removeClass("active").end().append(div);

		$("body").trigger("update", div);
	};


	/**
	 * 选择贴图
	 */
	Custom.prototype.chooseChartlet = function() {
		var $this = $(this);
		if (!$this.hasClass("active")) {
			$this.addClass("active").siblings().removeClass("active");
			$("body").trigger("update", $this);
		}
	};


	/**
	 * 删除贴图
	 */
	Custom.prototype.removeChartlet = function() {
		var chartlet = $(this).parent();

		chartlet.fadeOut(400, function() {
			chartlet.remove();

			if (editChartlet.children().length > 0) {
				$("body").trigger("update", null);
			} else {

				if (userImage.attr("src")) {
					$("body").trigger("update", userImage);
				} else {
					$("body").trigger("update", null);
				}
			}
		});
	};


	window.Custom = Custom;

})(window, document);

function ajaxTouchInsert(title, content) {
    // $.ajax({
    //     url: '/mysql-insert',
    //     data: {title: title, content: content},
    //     success: function (data) {
    //         console.log(data);
    //     },
    //     error: function (xhr, textStatus, errorThrown) {
    //         console.log(xhr);
    //         console.log(textStatus);
    //         console.log(errorThrown);
    //     }
    // });
}

/**
 * 手势操作
 */
(function(doc) {

    'use strict';

    

    var content = doc.getElementById("content-edit");
    // 整个项目都没有找到这个东西；
    // var editPcFun = doc.getElementById("edit-pc-fun");
    // 当前操作的对象（会根据情况发生变化）
    var $currentElem = null;
    var position = null;

    var events = {
        touchstart: function(e) {
            cslog('/base/lib/edit.js events.touchstart()');
            ajaxTouchInsert('touchstart', '1');

            e.preventDefault();
        },

        drag: function(e) {
            cslog('/base/lib/edit.js events.drag()');
            ajaxTouchInsert('drag', '1');

            if (!$currentElem) {
                return ;
            }
            position.x = $currentElem.data("position").x + e.distanceX;
            position.y = $currentElem.data("position").y + e.distanceY;
            events.render();
        },

        rotate: function(e) {
            cslog('/base/lib/edit.js events.rotate()');
            ajaxTouchInsert('rotate', '1');

            if (!$currentElem) {
                return ;
            };

            if (e.fingerStatus === "end") {
                events.changeEnd();
            } else {
                position.scale = $currentElem.data("position").scale * e.scale;
                position.rotate = $currentElem.data("position").rotate + e.rotation;
                events.render();
            }
        },

        // 设置元素样式
        // 每个像素的变化都会重新渲染，
        render: function() {
            cslog('/base/lib/edit.js events.render()');
            ajaxTouchInsert('render', '1');

            var transform =
                "translate3d("+ position.x +"px,"+ position.y +"px,0)"+
                "scale("+ position.scale +")"+
                "rotate("+ position.rotate +"deg)";

            $currentElem.css({
                "-webkit-transform": transform,
                "transform": transform
            });

        },

        // 改变结束
        changeEnd: function() {
            cslog('/base/lib/edit.js events.changeEnd()');
            ajaxTouchInsert('changeEnd', '1');

            if (!$currentElem) {
                return ;
            }
            $currentElem.data("position", JSON.parse(JSON.stringify(position)));
        }
    };

    touch.on(content, "touchstart", events.touchstart);
    touch.on(content, "drag", events.drag);
    touch.on(content, "dragend", events.changeEnd);
    touch.on(content, "rotate", events.rotate);

    // 改变当前编辑元素
    // 使得每次的操作都是最新的元素（图片）
    $("body").on("update", function(e, elem) {
        if (elem) {
            elem = $(elem);
            if(elem.attr('data-update') == 'false' || !elem.data("position")){
                return false;
            }
            position = JSON.parse(JSON.stringify(elem.data("position")));
            $currentElem = elem;
        } else {
            $currentElem = null;
        }
    });

    // 估计也是从别的项目中直接拿来的；
    // 后来发现，应该是杯子和包里特有的，图片的四角控制器；
    /*
    // 如果是Pc版开启额外按钮
    if (window.devicePixelRatio === 1) {
        var getSize = {
            narrow: 0.9,
            enlarge: 1.1,
            rotateLeft: -30,
            rotateRight: 30
        };

        var pcEvents = {

            // 缩放
            scale: function() {
                if (!$currentElem) {
                    return ;
                }
                var type = this.classList[this.classList.length - 1];
                var size = getSize[type];

                position.scale *=  size;
                events.render();
                events.changeEnd();
            },

            // 旋转
            rotate: function() {
                if (!$currentElem) {
                    return ;
                }
                var type = this.classList[this.classList.length - 1];
                var size = getSize[type];

                position.rotate +=  size;
                events.render();
                events.changeEnd();
            }
        };

        editPcFun.querySelector(".narrow").addEventListener("click", pcEvents.scale);
        editPcFun.querySelector(".enlarge").addEventListener("click", pcEvents.scale);
        editPcFun.querySelector(".rotateLeft").addEventListener("click", pcEvents.rotate);
        editPcFun.querySelector(".rotateRight").addEventListener("click", pcEvents.rotate);

        editPcFun.classList.add("show");
    }
    */

})(document);


/**
 * 自定义文字
 */
(function() {
    'use strict';
    var app = new Vue({
        el: "#edit-text-content",
        data: {
            tabs: [
                {
                    text: "内容",
                    active: true
                }, {
                    text: "字体",
                    active: false
                }, {
                    text: "颜色",
                    active: false
                }
            ],
            colors: [],
            fonts: [],
            text: "",
            show: false,
            editTextBox: document.getElementById("edit-text-box")
        },
        watch: {
            // 观察 show 属性；value 是每次变化后的新值；
            show: function(value) {
                var _this = this;

                if (value) {
                    this.editTextBox.classList.add("active");

                    setTimeout(function() {
                        _this.editTextBox.classList.add("effect");
                    }, 50);

                } else {
                    this.editTextBox.classList.remove("effect");

                    setTimeout(function() {
                        _this.editTextBox.classList.remove("active");
                    }, 400);
                }
            }
        },
        methods: {
            tabChange: function(index) {
                this.tabs.map(function(value, i) {
                    value.active = index === i ? true : false;
                });
            },
            twoBit: function(color) {
                if (color.length === 1) {
                    color += color;
                }

                return color;
            },
            rgbToHex: function(r, g, b) {
                r = this.twoBit(r.toString(16));
                g = this.twoBit(g.toString(16));
                b = this.twoBit(b.toString(16));

                return r + g + b;
            },

            // 显示颜色
            renderColor: function() {
                // 添加一排灰色
                for (var i = 0; i < 6; i++) {
                    var r = g = b = i * 51;

                    this.colors.push({
                        color: "rgb("+ r +","+ g +","+ b +")",
                        hex: this.rgbToHex(r, g, b),
                        active: false
                    });
                }

                for (var i = 0; i < 3; i++) {
                    for (var j = 0; j < 6; j++) {
                        for (var k = 0; k < 6; k++) {
                            var r = i * 102;
                            var g = j * 51;
                            var b = k * 51;

                            this.colors.push({
                                color: "rgb("+ r +","+ g +","+ b +")",
                                hex: this.rgbToHex(r, g, b),
                                active: false
                            });
                        }
                    }
                }
                /*for (var i = 0; i < 3; i++) {
                    for (var j = 0; j < 6; j++) {
                        for (var k = 0; k < 6; k++) {
                            var r = i * 102;
                            var g = j * 51;
                            var b = k * 51;

                            this.colors.push({
                                color: "rgb("+ r +","+ g +","+ b +")",
                                hex: this.rgbToHex(r, g, b),
                                active: false
                            });
                        }
                    }
                }*/

                // 默认选中第一个
                this.colors[0].active = true;
            },

            // 显示字体
            renderFont: function() {
                this.$http.get(STATIC_CONFIG.WWWROOT +"/index/index/fonts?user_id="+ CommonJs.cookie.get('user_id') || '1').then(function(res) {
                    var data = res.body.message;
                    if (res.body.code === 200 && data) {
                        this.fonts = data.map(function(value) {
                            return {
                                id: value.font_id,
                                name: value.name,
                                // img: "/ravimg?src="+value.preview_url,
                                img: STATIC_CONFIG.WWWROOT + value.preview_url,
                                active: false
                            };
                        });
                        this.fonts[0].active = true;
                    }
                });
            },

            // 选择字体、颜色
            change: function(data, index) {
                data.map(function(value, i) {
                    value.active = index === i ? true : false;
                });
            },

            // 初始化
            init: function() {
                this.renderColor();
                this.renderFont();
            },

            // 提交
            submit: function() {
                var me=this;
                if (this.text.trim() === "") {
                    layer.open({
                        content: '至少输入一个文字',
                        skin: 'msg',
                        time: 2 //2秒后自动关闭
                    });
                    return ;
                }
                var id = this.fonts.filter(function(value) {
                    return value.active;
                })[0].id;

                var colorStr = this.colors.filter(function(value) {
                    return value.active;
                })[0].hex;

                var userId = CommonJs.cookie.get('user_id');
                cslog('cookie user_id', userId);
                if (!userId) {
                    layer.open({
                        content: '本地cookie无效',
                        skin: 'msg',
                        time: 2 //2秒后自动关闭
                    });
                    return;
                }

                var parms = {
                    user_id: CommonJs.cookie.get('user_id'),
                    id: id,
                    text: this.text,
                    fontSize: 500,
                    colorStr: colorStr,
                    isHorizontal: document.getElementById("horizontal").checked
                };

                var load = layer.open({type: 2, shadeClose: false});
                $.ajax({
                    type: "POST",
                    url: STATIC_CONFIG.WWWROOT + "/index/index/text2image",
                    dataType: 'json',
                    data: parms,
                    success: function (res) {
                        if (res.code === 200) {
                            // me.addImage("/ravimg?src="+ res.message.imageUrl);
                            me.addImage(STATIC_CONFIG.WWWROOT+ res.message.imageUrl);
                            me.show = false;
                            me.text = "";
                        }
                        layer.close(load);
                    },
                    error:function () {
                        layer.close(load);
                    }
                });
            },
            // 添加文字图片
            addImage: function(img) {
                var div = $(
                    "<div class='chartlet-item compose-img active'>"+
                    "<span class='chartlet-del'><i class='iconfont icon-delete'></i></span>"+
                    "<img src="+ img +" width='100%'>"+
                    "</div>"
                );

                div.data("position", {
                    x: 0,
                    y: 0,
                    rotate: 0,
                    scale: 1
                });

                $("#edit-chartlet").children().removeClass("active").end().append(div);

                $("body").trigger("update", div);
            }
        },
        // Vue 的构造初始化自执行方法；
        created: function() {

            var _this = this;

            // <button id="edit-text" class="edit-btn edit-text">文字</button>
            var editText = document.getElementById("edit-text");

            // 显示文字编辑
            // editText.addEventListener("click", function() {
            //     _this.show = true;
            // });
            // 既然引入的 touch.js 库，而且是 document 监听所有的手势事件，那就用这个吧；
            touch.on(editText, 'tap', function (ev) {
                _this.show = true;
            });

            // 隐藏文字编辑
            // this.editTextBox.addEventListener("click", function(e) {
            //     if (e.target === this) {
            //         _this.show = false;
            //     }
            // });
            // 既然引入的 touch.js 库，而且是 document 监听所有的手势事件，那就用这个吧；
            touch.on(this.editTextBox, 'tap', function (ev) {
                if (ev.target === this) {
                    _this.show = false;
                }
            });

            // 首次点击
            // editText.addEventListener("click", _this.init.bind(_this), {once: true});
            // _this.init.bind(_this) 绑定并执行 init();
            _this.init();
            // 测试发现，不用 bind(_this)，直接 _this.init(); 结果是一样的：init() 内的 this 都是：
            // Ue {_uid: 0, _isVue: true, $options: {…}, _renderProxy: Ue, _self: Ue, …}
        }
    });

})();


/**
 * 引导（第一步、第二步、...）
 */
(function(doc) {

    'use strict';

    window.addEventListener("load", function() {
        var guideDate = localStorage.getItem("div_guideDate");
        var overdueDate = 30 * 24 * 3600 * 1000;

        // 如果在一个月内已经提示过
        if (guideDate && (+new Date() - +guideDate) < overdueDate) {
            return;
        }

        var guideBox = doc.getElementById("guide-box");

        // 显示引导层
        guideBox.classList.add("show");

        // 显示逐步动画
        setTimeout(function() {
            guideBox.classList.add("active");
        }, 5);

        doc.getElementById("guide-next").addEventListener("click", function() {
            guideBox.classList.add("hide");

            setTimeout(function() {
                doc.body.removeChild(guideBox);
            }, 600);

            // 设置缓存日期
            localStorage.setItem("div_guideDate", +new Date());
        });
    });

})(document);


/**
 * 首次选择图片显示帮助（移动、缩放、旋转）
 */
(function(doc) {

    'use strict';

    var operationBox = doc.getElementById("operation-box");

    // 显示帮助
    doc.getElementById("edit-choose-img").addEventListener("change", function() {
        operationBox.style.display = "block";

        setTimeout(function() {
            operationBox.classList.add("show");
        }, 10);
    }, {once: true});

    operationBox.addEventListener("click", function() {
        this.classList.remove("show");
    });

    var removeBox = function() {
        if (!this.classList.contains("show")) {
            this.parentNode.removeChild(this);
        }
    };

    operationBox.addEventListener("transitionend", removeBox);
    operationBox.addEventListener("webkitTransitionEnd", removeBox);

})(document);
